package com.lightsh.widgetdemo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.prefs.Preferences;

import com.lightsh.util.NewsInfo;
import com.lightsh.util.Utility;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetService extends Service implements Runnable {
	
	private static final boolean DEBUG = true;

	private static final String TAG = "WidgetService";
	private static final String FLAG_UPDATE_ALL = "com.lightsh.widgetdemo.WidgetService.UpdateAll";
	public static final String FLAG_REGET_DATA = "con.lightsh.widgetdemo.WidgetService.RegetData";
	
	
	private static Object mLock = new Object();
	private static boolean mbThreadRunning = false;
	private static boolean mbRegetThreadRunning = false;
	
	// 使用队列记录widget的id值能有效控制顺序等问题
	private static Queue<Integer> mWidgetIds = new LinkedList<Integer>();
	
	// 使用列表来存储数据
	private static List<NewsInfo> mNewsList = new ArrayList<NewsInfo>();
	private static int mCurrentIndex = 0;
	
	
	public static void updateWidgetIds(int [] ids){
		synchronized (mLock) {
			for(int id : ids){
				mWidgetIds.add(id);
			}	
		}
	}
	
	private static int getNextVidgetId(){
		synchronized (mLock) {
			if(mWidgetIds.peek() == null){
				return AppWidgetManager.INVALID_APPWIDGET_ID;
			}else{
				return mWidgetIds.poll();
			}
		}
	}
	
	private static boolean hasMoreUpdates(){
		synchronized (mLock) {
			if(!mWidgetIds.isEmpty()){
				return true;
			}else{
				mbThreadRunning = false;
				return false;
			}
		}
	}
	

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if(null != intent){
			if(FLAG_UPDATE_ALL.equals(intent.getAction())){
				// 需要获取最新的widgetID值
				AppWidgetManager widgetManaget = AppWidgetManager.getInstance(this);
				updateWidgetIds(widgetManaget.getAppWidgetIds(new ComponentName(this, WidgetDemo.class)));
				if(!hasMoreUpdates()){
					if(DEBUG){
						Log.e(TAG, "no more widgets exist, stopSelf!");
					}
					stopSelf();
					return;
				}
			}else{
				if(FLAG_REGET_DATA.equals(intent.getAction())){
					AppWidgetManager widgetManaget = AppWidgetManager.getInstance(this);
					int[] widgetIds = widgetManaget.getAppWidgetIds(new ComponentName(this, WidgetDemo.class));
					if(widgetIds == null || widgetIds.length == 0){
						if(DEBUG){
							Log.e(TAG, "no more widgets exist in FLAG_REGET_DATA, stopSelf!");
						}
						stopSelf();
						return;
					}
					// 重新获取数据
					regetData();
				}
			}
		}
		
		synchronized (mLock) {
			if(!mbThreadRunning){
				mbThreadRunning = true;
				new Thread(this).start();
			}
		}
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public void run() {
//		if(DEBUG){
//			Log.e(TAG, "update widget run");
//		}
		
		// 进行更新控件操作
		AppWidgetManager widgetManager = AppWidgetManager.getInstance(WidgetService.this);
		RemoteViews remoteView = null;
		while(hasMoreUpdates()){
			int widgetId = getNextVidgetId();
			
			// 获取新闻数据
			NewsInfo info = getNewsInfo(this);
			remoteView = WidgetDemo.getFitRemoteView(this, info);
			widgetManager.updateAppWidget(widgetId, remoteView);
//			if(DEBUG){
//				Log.e(TAG, "update widget id:" + widgetId);
//			}
			
		}
		
		// 设定下一个的更新时间
		Intent alarmIntent = new Intent(FLAG_UPDATE_ALL);
		alarmIntent.setClass(this, WidgetService.class);
		PendingIntent pending = PendingIntent.getService(this, 0, alarmIntent, 0);
		
		long interval = getUpdateInterval(this);
		Time time = new Time();
		time.set(System.currentTimeMillis() + interval);
		AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC_WAKEUP, time.toMillis(true), pending);
		
		// 停止服务
		synchronized (mLock) {
			
			// nIndex增加
			mCurrentIndex++;
			
			if(!mbThreadRunning && !mbRegetThreadRunning){
				stopSelf();
			}
		}
	}
	
	public static final long getUpdateInterval(Context context){
		return Utility.WIDGET_REFRESH_INIT_INTERVAL;
	}
	public static final long getRegetInterval(Context context){
		SharedPreferences preferences = context.getSharedPreferences(Utility.PREFERENCES_WIDGET_INFO, 0);
		return preferences.getLong(Utility.SETTING_REGET_DATA_INTERVAL, Utility.WIDGET_REGET_DATA_INTERVAL);
	}
	
	/**
	 * 该方法可能会通过网络请求数据,要在线程中调用
	 * @param context
	 * @return
	 * 
	 */
	public static final NewsInfo getNewsInfo(Context context){
		// 获取新闻
		synchronized (mLock) {
			if(mNewsList.size() == 0){
				if(Utility.isNetworkAvailable(context) && !mbRegetThreadRunning){
					// TODO 通过网络请求数据
					if(DEBUG){
						Log.e(TAG, "getNewsInfo data empty, request network data!");
					}
					
					parseData("");
				}
			}
			if(mNewsList.size() == 0){
				// 没有获取到数据
				if(mbRegetThreadRunning){
					if(DEBUG){
						Log.e(TAG, "getNewsInfo data empty, wait for regetThread!");
					}
					return new NewsInfo("正在获取数据...", "", "", "");
				}else{
					if(DEBUG){
						Log.e(TAG, "getNewsInfo data empty, error!");
					}
					return new NewsInfo("获取数据出错", "获取数据出错", "", "");
				}
			}else{
				if(mCurrentIndex >= mNewsList.size() || mCurrentIndex < 0){
					mCurrentIndex = 0;
				}
				return mNewsList.get(mCurrentIndex);
			}
		}
	}
	
	public void regetData(){
		synchronized (mLock) {
			if(!mbRegetThreadRunning){
				if(DEBUG){
					Log.e(TAG, "regetData thread begin run");
				}
				mbRegetThreadRunning = true;
				new Thread(new Runnable() {
					
					public void run() {
//						try{
//							Thread.sleep(10000);
//						}catch(Exception e){
//							
//						}
						// TODO 获取数据
						parseData("");
						
						// 重新设置闹钟
						Intent alarmIntent = new Intent(FLAG_REGET_DATA);
						alarmIntent.setClass(WidgetService.this, WidgetService.class);
						PendingIntent pending = PendingIntent.getService(WidgetService.this, 0, alarmIntent, 0);
						
						long interval = getRegetInterval(WidgetService.this);
						Time time = new Time();
						time.set(System.currentTimeMillis() + interval);
						AlarmManager alarmManager = (AlarmManager)WidgetService.this.getSystemService(Context.ALARM_SERVICE);
						alarmManager.set(AlarmManager.RTC_WAKEUP, time.toMillis(true), pending);
						
						// 判断是否可以结束
						synchronized (mLock) {
							mbRegetThreadRunning = false;
							if(!mbThreadRunning && !mbRegetThreadRunning){
								stopSelf();
							}
						}
						
					}
				}).start();
			}else{
				if(DEBUG){
					Log.e(TAG, "regetData thread is running!may be error!");
				}
			}
		}
	}
	
	private static void parseData(String dataString){
		synchronized (mLock) {
			// TODO 判断数据是否合法
			
			// 清空列表
			mNewsList.clear();
			
			// TODO 将数据写入列表
			mNewsList.add(new NewsInfo("茅台涨价调查", "凤凰网", "", ""));
			mNewsList.add(new NewsInfo("沈阳高校毕业生就业率92.1% 博士优势最明显", "中新网", "", ""));
			mNewsList.add(new NewsInfo("京东融资5亿美元:电子商务红海生存术", "凤凰网", "", ""));
		}
	}
	
}
